<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="领料人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pickBy">
              <a-row :gutter="4">
                <a-col :span="18">
                  <a-input v-model="model.pickBy" placeholder="请选择领料人"></a-input>
                </a-col>
                <a-col :span="6">
                  <a-button @click="handleSelectEmployee" type="primary" :loading="confirmLoading">选择</a-button>
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="领料部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pickOrgName">
              <a-input v-model="model.pickOrgName" placeholder="" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="领料日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pickDate">
              <j-date
                placeholder="请选择领料日期"
                v-model="model.pickDate"
                :show-time="true"
                date-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="备注"
              :labelCol="{ xs: { span: 24 }, sm: { span: 1 } }"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 22 } }"
              prop="remarks"
            >
              <a-input v-model="model.remarks" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="退料明细" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="tslProDeficitPickBillDetailTable.loading"
          :columns="tslProDeficitPickBillDetailTable.columns"
          :dataSource="tslProDeficitPickBillDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="false"
          :toolbar="false"
        />
      </a-tab-pane>
    </a-tabs>
    <select-pick-user-modal ref="selectPickUserModal" @handlerOk="handleSelectEmployeeOk" />
  </a-spin>
</template>

<script>
import { getAction, postAction, putAction } from '@api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import store from '@/store'
import EmployeeListModal from '@/components/tsl/modules/EmployeeListModal.vue'
import { getDate } from '../../../utils'
import SelectPickUserModal from '../SelectPickUserModal.vue'

export default {
  name: 'TslProDeficitPickBillForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    EmployeeListModal,
    SelectPickUserModal,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {},
      validatorRules: {
        pickBy: [{ required: true, message: '请选择领料人!' }],
        pickDate: [{ required: true, message: '请选择领料日期!' }],
      },
      refKeys: ['tslProDeficitPickBillDetail'],
      tableKeys: ['tslProDeficitPickBillDetail'],
      activeKey: 'tslProDeficitPickBillDetail',
      // 领料赤字单子表
      tslProDeficitPickBillDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '领料单号',
            key: 'pickCode',
            dataIndex: 'pickCode',
            align: 'center',
            type: JVXETypes.normal,
            minWidth: 120,
            sorter: (a, b) => a.code.localeCompare(b.code, 'en'),
          },
          {
            title: '客户物料编码',
            key: 'customCode',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: '140px',
            defaultValue: '',
          },
          {
            title: '物料编码',
            key: 'productCode',
            dataIndex: 'productCode',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: 120,
            defaultValue: '',
          },
          {
            title: '物料名称',
            key: 'productBatchNo',
            dataIndex: 'productBatchNo',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: 300,
            defaultValue: '',
          },
          {
            title: '规格型号',
            key: 'materialSpec',
            dataIndex: 'materialSpec',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: 100,
          },
          {
            title: '主单位',
            key: 'meUnit_dictText',
            dataIndex: 'meUnit_dictText',
            dictCode: 'ji_unit',
            type: JVXETypes.select,
            align: 'center',
            minWidth: 100,
            disabled: true,
          },
          {
            title: '主数量',
            key: 'applyQuantity',
            dataIndex: 'applyQuantity',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: 120,
          },
          {
            title: '已退数量',
            key: 'mainQuantity',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: 120,
          },
          {
            title: '批次号',
            key: 'batchNumber',
            dataIndex: 'batchNumber',
            align: 'center',
            minWidth: 150,
            disabled: true,
          },
          {
            title: '物料批号',
            key: 'materialBatchNumber',
            dataIndex: 'materialBatchNumber',
            align: 'center',
            minWidth: 150,
            disabled: true,
          },
          {
            title: '退料数量',
            key: 'backQuantity',
            type: JVXETypes.input,
            align: 'center',
            minWidth: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            align: 'center',
            minWidth: '300px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ],
      },
      url: {
        add: '/pro/tslProDeficitPickBill/add',
        edit: '/pro/tslProDeficitPickBill/edit',
        queryById: '/pro/tslProDeficitPickBill/queryById',
        inbound: '/wms/inbound/inbound-order/add',
        tslProDeficitPickBillDetail: {
          list: '/pro/tslProDeficitPickBill/queryTslProDeficitPickBillDetailByMainId',
        },
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  methods: {
    //选择员工方法
    handleSelectEmployeeOk(data) {
      console.log('选择员工：', data)
      if (data) {
        this.model.pickBy = data.realname
        this.model.pickOrgCode = data.orgCode
        this.model.pickOrgName = data.orgCodeTxt
        this.$forceUpdate() //重新渲染UI
      }
    },
    //绑定所属员工
    handleSelectEmployee() {
      this.$refs.selectPickUserModal.visible = true
    },
    add(rows, type) {
      this.reset()
      this.model.billType = type
      const Decimal = require('decimal.js')
      if (rows && rows.length > 0) {
        rows.forEach((item) => {
          item.backQuantity = new Decimal(item.applyQuantity.toString())
            .minus(new Decimal(item.mainQuantity.toString()))
            .toNumber()
        })
        this.tslProDeficitPickBillDetailTable.dataSource = rows
      }
    },
    // 修改 edit 方法
    edit(record) {
      console.log(record)
      this.model = record
      this.model.pickOrgName = record.pickOrgCode_dictText
      this.model.code = record.billCode
      record.applyQuantity = ''
      record.mainQuantity = ''
      this.tslProDeficitPickBillDetailTable.dataSource = []
      this.tslProDeficitPickBillDetailTable.dataSource.push(record)
    },
    async handleOk() {
      //  校验主表单
      const mainFormValid = await new Promise((resolve) => {
        this.$refs.form.validate((valid) => resolve(valid))
      })
      if (!mainFormValid) return

      let hasMissingFields = false
      this.tslProDeficitPickBillDetailTable.dataSource.forEach((row, index) => {
        if (!row.backQuantity || row.backQuantity === '') {
          hasMissingFields = true
          this.$message.error(`第 ${index + 1} 行的退料数量不能为空`)
        } else {
          const applyQuantity = Number(row.applyQuantity) || 0
          const backQuantity = Number(row.backQuantity) || 0
          const mainQuantity = Number(row.mainQuantity) || 0
          if (backQuantity + mainQuantity > applyQuantity) {
            hasMissingFields = true
            this.$message.error(`第 ${index + 1} 行的退料数量不能大于主数量-已退数量`)
          }
        }
      })
      if (hasMissingFields) return

      //  调用接口提交（根据实际接口调整）
      this.confirmLoading = true
      this.model.tslProDeficitPickBillDetailList = this.tslProDeficitPickBillDetailTable.dataSource
      try {
        const url = this.model.code ? this.url.edit : this.url.add // 编辑/新增判断
        await postAction(url, this.model).then((res) => {
          if (res.success && res.result && this.model) {
            let billCode = res.result
            let details = []
            this.model.tslProDeficitPickBillDetailList.forEach((item) => {
              const receivedQty = parseFloat(item.backQuantity) || 0
              const rate = parseFloat(item.coRate) || 0
              console.log('coRate', item.coRate, receivedQty * rate)
              details.push({
                customerMaterialCode: item.customCode,
                materialCode: item.productCode,
                materialName: item.productBatchNo,
                specificationModel: item.materialSpec,
                unit: item.meUnit,
                quantity: item.backQuantity,
                secondaryUnit: item.auUnit || 0,
                secondaryQuantity: receivedQty * rate,
                materialBatchNumber: item.materialBatchNumber,
                targetWarehouseCode: item.warehouseCode,
                warehouseCode: item.warehouseCode, //item.wareNo,
              })
            })

            const mergedMap = new Map()
            details.forEach((item) => {
              const key = `${item.materialCode}|${item.targetWarehouseCode}|${item.warehouseCode}`
              const itemQty = Number(item.quantity) || 0
              if (mergedMap.has(key)) {
                const existing = mergedMap.get(key)
                existing.quantity += itemQty
              } else {
                mergedMap.set(key, { ...item, quantity: itemQty })
              }
            })
            let datas = Array.from(mergedMap.values())

            const groups = new Map()
            datas.forEach((item) => {
              const key = `${item.targetWarehouseCode}|${item.warehouseCode}`
              if (groups.has(key)) {
                groups.get(key).push(item)
              } else {
                groups.set(key, [item])
              }
            })
            groups.forEach((groupItems, groupKey) => {
              if (groupItems.length > 0) {
                putAction('/sys/fillRule/executeRuleByCode/deficit_inbound_code', {}).then((rse) => {
                  if (rse.success) {
                    // 原料领料赤字	5   material
                    // 包材领料赤字	6   package
                    // 通用领料赤字	7   common
                    let inbound = {}
                    if (this.model.billType == 'material') {
                      inbound.entryType = 5
                      inbound.entryNumber = 'YL' + rse.result
                    }
                    if (this.model.billType == 'package') {
                      inbound.entryType = 6
                      inbound.entryNumber = 'BC' + rse.result
                    }
                    if (this.model.billType == 'common') {
                      inbound.entryType = 7
                      inbound.entryNumber = 'TY' + rse.result
                    }
                    if (this.model.billType == 'sample') {
                      inbound.entryType = 18
                      inbound.entryNumber = 'YP' + rse.result
                    }
                    inbound.documentNumber = billCode
                    inbound.targetWarehouseCode = groupItems[0].targetWarehouseCode
                    inbound.warehouseCode = groupItems[0].warehouseCode
                    inbound.inboundOrderItemList = groupItems
                    postAction(this.url.inbound, inbound)
                  }
                })
              }
            })
            this.$message.success('提交成功')
            this.$emit('ok') // 触发提交成功事件，通知模态框
          }
        })
      } catch (error) {
        this.$message.error('提交失败：' + (error.message || '网络异常'))
      } finally {
        this.confirmLoading = false
      }
    },
    reset() {
      let d = getDate('day', 0)
      this.model = {
        id: undefined,
        code: undefined,
        billType: undefined,
        workshopCode: '',
        wareNo: '',
        workshopPlan: '',
        pickBy: '',
        pickDate: d,
        remark: '',
      }
    },
    addBefore() {
      this.tslProPackagePickBillDetailTable.dataSource = []
    },
  },
}
</script>

<style scoped></style>
